<template>
  <article
    class="bg-white rounded-xl shadow-sm overflow-hidden hover:shadow-md transition-shadow mb-4"
  >
    <!-- 帖子头部 -->
    <div class="p-4 flex items-center justify-between">
      <div class="flex items-center space-x-3">
        <!-- 头像兜底：使用内联逻辑确保安全访问 -->
        <img
          :src="post.user?.avatar || 'https://picsum.photos/seed/user/60/60'"
          alt="用户头像"
          class="w-10 h-10 rounded-full object-cover"
        />
        <div>
          <!-- 用户名兜底：优先昵称→登录ID→匿名用户 -->
          <h3 class="font-medium text-gray-900">
            {{ post.user?.nickname || post.user?.loginId || "匿名用户" }}
          </h3>
          <p class="text-xs text-gray-500">
            {{ formatTime(post.createTime) }} ·
            {{ post.cateName || "未分类" }}
          </p>
        </div>
      </div>
      <!-- 置顶标签：支持字符串和数字类型的判断 -->
      <div
        v-if="String(post.postTop) === '1'"
        class="text-xs text-yellow-500 font-medium mr-2"
      >
        置顶
      </div>
      <!-- 更多选项按钮（当canDelete和canEdit都为true时显示） -->
      <div v-if="post.canDelete && post.canEdit" class="relative">
        <button 
          class="text-gray-400 hover:text-gray-600"
          @click.stop="toggleMoreOptions"
        >
          <i class="fa fa-ellipsis-h"></i>
        </button>
        <!-- 下拉菜单 -->
        <div 
          v-if="showMoreOptions"
          class="absolute right-0 mt-2 w-48 bg-white rounded-md shadow-lg py-1 z-10"
        >
          <button 
            class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100 flex items-center"
            @click.stop="handleDeletePost"
            :disabled="isDeletingPost"
          >
            <i class="fa fa-trash-o mr-2"></i>
            <span v-if="isDeletingPost">
              <i class="fa fa-spinner fa-spin mr-2"></i>删除中...
            </span>
            <span v-else>删除</span>
          </button>
        </div>
      </div>
      <!-- 占位元素，保持布局一致性 -->
      <div v-else class="w-6"></div>
    </div>

    <!-- 其余模板内容保持不变 -->
    <div class="px-4 pb-4">
      <h2
        class="text-lg font-semibold mb-2 text-gray-900 hover:text-primary transition-colors cursor-pointer"
        @click="goToDetail"
      >
        {{ post.title || "无标题" }}
      </h2>
      <!-- 内容去HTML标签：处理空内容兜底 -->
      <p class="text-gray-600 mb-3 line-clamp-2">
        {{ post.content ? stripHtml(post.content) : "无内容" }}
      </p>

      <!-- 帖子图片（多图高度统一，空数组判断） -->
      <div v-if="post?.media?.length > 0" class="mb-4">
        <div v-if="post?.media?.length === 1" class="rounded-lg overflow-hidden">
          <img
            :src="post.media[0]"
            alt="帖子图片"
            class="w-full h-48 object-cover"
          />
        </div>
        <div v-else class="grid grid-cols-2 gap-2 rounded-lg overflow-hidden">
          <img
            v-for="(image, index) in post.media"
            :key="index"
            :src="image"
            alt="帖子图片"
            class="w-full h-36 object-cover"
          />
        </div>
      </div>

      <!-- 互动区域 -->
      <div class="flex items-center justify-between text-gray-500 text-sm">
        <div class="flex items-center space-x-4">
          <!-- 点赞按钮：禁用状态+加载中动画 -->
          <button
            class="flex items-center space-x-1 hover:text-primary transition-colors"
            @click.prevent="toggleLike"
            :disabled="isLiking"
          >
            <i
              :class="[
                'fa',
                post.liked ? 'fa-heart text-primary' : 'fa-heart-o',
                isLiking ? 'fa-spin' : '',
              ]"
            ></i>
            <span>{{ post.likeCount }}</span>
          </button>
          <!-- 评论按钮 -->
          <button
            class="flex items-center space-x-1 hover:text-primary transition-colors"
            @click.prevent="toggleCommentSection"
          >
            <i class="fa fa-comment-o"></i>
            <span>{{ post.commentCount }}</span>
          </button>
          <!-- 阅读量 -->
          <span class="flex items-center space-x-1 text-gray-400">
            <i class="fa fa-eye"></i>
            <span>{{ post.readCount }}</span>
          </span>
        </div>
        <div class="flex items-center space-x-4">
          <!-- 收藏按钮 -->
          <button
            class="flex items-center space-x-1 hover:text-primary transition-colors"
            @click.prevent="toggleCollect"
            :disabled="isCollecting"
          >
            <i
              :class="[
                'fa',
                post.collected ? 'fa-bookmark text-primary' : 'fa-bookmark-o',
                isCollecting ? 'fa-spin' : '',
              ]"
            ></i>
          </button>
        </div>
      </div>

      <!-- 评论区域（分页逻辑优化） -->
      <div v-if="showComments" class="mt-4 pt-4 border-t border-gray-100">
        <!-- 加载中 -->
        <div v-if="isLoadingComments" class="text-center py-3">
          <div
            class="inline-block animate-spin rounded-full h-4 w-4 border-2 border-primary border-t-transparent"
          ></div>
        </div>
        <div v-else>
          <!-- 评论列表 -->
          <div v-if="comments.length > 0" class="space-y-3 mb-3">
            <div
              v-for="comment in comments"
              :key="comment.id"
              class="text-sm bg-gray-50 p-3 rounded-lg"
            >
              <div class="flex items-start space-x-2">
                <!-- 评论者头像兜底 -->
                <img
                  :src="
                    comment.userRespDTO?.avatar ||
                    'https://picsum.photos/seed/user/60/60'
                  "
                  alt="用户头像"
                  class="w-6 h-6 rounded-full object-cover mt-1"
                />
                <div class="flex-1">
                  <div class="flex items-center space-x-2 mb-1">
                    <span class="font-medium text-gray-800">{{
                      comment.userRespDTO?.nickname ||
                      comment.userRespDTO?.loginId ||
                      "匿名用户"
                    }}</span>
                    <span class="text-xs text-gray-400">{{
                      formatTime(comment.createTime)
                    }}</span>
                  </div>
                  <p class="text-gray-600">{{ comment.content }}</p>
                  <!-- 评论互动 -->
                  <div
                    class="flex items-center space-x-3 mt-2 text-xs text-gray-500"
                  >
                    <!-- 评论点赞：加载状态控制 -->
                    <button
                      class="hover:text-primary transition-colors"
                      @click.prevent="toggleCommentLike(comment)"
                      :disabled="commentLikeStatus[comment.id]"
                    >
                      <i
                        :class="[
                          'fa',
                          comment.liked
                            ? 'fa-heart text-primary'
                            : 'fa-heart-o',
                          commentLikeStatus[comment.id] ? 'fa-spin' : '',
                        ]"
                      ></i>
                      <span>{{ comment.likeCount }}</span>
                    </button>
                    <!-- 回复按钮 -->
                    <button
                      class="hover:text-primary transition-colors"
                      @click.prevent="showReplyInput(comment)"
                    >
                      <i class="fa fa-comment-o"></i>
                      <span>回复</span>
                    </button>
                    <!-- 删除按钮（仅自己的评论显示） -->
                    <button
                      v-if="isOwnComment(comment)"
                      class="hover:text-red-500 transition-colors"
                      @click.prevent="DeleteComment(comment.id)"
                      :disabled="isDeleting[comment.id]"
                    >
                      <i
                        :class="[
                          'fa',
                          'fa-trash-o',
                          isDeleting[comment.id] ? 'fa-spin' : '',
                        ]"
                      ></i>
                      <span>删除</span>
                    </button>
                  </div>
                  <!-- 回复输入框（绑定逻辑优化） -->
                  <div v-if="replyToComment?.id === comment.id" class="mt-3">
                    <input
                      v-model="replyContent"
                      type="text"
                      :placeholder="`回复 @${
                        comment.userRespDTO?.nickname ||
                        comment.userRespDTO?.loginId ||
                        '匿名用户'
                      }`"
                      comment.userRespDTO
                      class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50"
                      @keyup.enter="submitReply"
                      @blur="cancelReply"
                    />
                    <div class="flex justify-end mt-1">
                      <button
                        class="px-3 py-1 text-sm text-gray-500 hover:text-gray-700 mr-2"
                        @click.prevent="cancelReply"
                      >
                        取消
                      </button>
                      <button
                        class="px-3 py-1 text-sm bg-primary text-white rounded hover:bg-primary/90"
                        @click.prevent="submitReply"
                        :disabled="!replyContent.trim()"
                      >
                        发送
                      </button>
                    </div>
                  </div>
                  <!-- 子回复列表（安全访问嵌套属性） -->
                  <div
                    v-if="comment.replies && comment.replies.length > 0"
                    class="mt-3 pl-4 border-l-2 border-gray-100 space-y-2"
                  >
                    <div
                      v-for="reply in comment.replies"
                      :key="reply.id"
                      class="text-sm"
                    >
                      <div class="flex items-start space-x-2">
                        <!-- 回复者头像兜底 -->
                        <img
                          :src="
                            reply.userRespDTO?.avatar ||
                            'https://picsum.photos/seed/user/60/60'
                          "
                          alt="回复者头像"
                          class="w-5 h-5 rounded-full object-cover mt-1"
                        />
                        <div class="flex-1">
                          <span class="font-medium text-gray-800 text-xs">{{
                            reply.userRespDTO?.nickname ||
                            reply.userRespDTO?.loginId ||
                            "匿名用户"
                          }}</span>
                          <span class="text-gray-600 ml-1">{{
                            reply.content
                          }}</span>
                          <div
                            class="flex items-center space-x-3 mt-1 text-xs text-gray-400"
                          >
                            <span>{{ formatTime(reply.createTime) }}</span>
                            <button
                              class="hover:text-primary"
                              @click.prevent="showReplyInput(comment, reply)"
                            >
                              回复
                            </button>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- 空评论提示 -->
          <div v-else class="text-center py-3 text-gray-500 text-sm">
            暂无评论，快来抢沙发吧！
          </div>
          <!-- 加载更多评论（分页状态控制） -->
          <div v-if="hasMoreComments" class="text-center py-2">
            <button
              class="text-sm text-primary hover:text-primary/80"
              @click="loadMoreComments"
              :disabled="isLoadingComments"
            >
              <span
                v-if="isLoadingComments"
                class="inline-block animate-spin rounded-full h-3 w-3 border-2 border-primary border-t-transparent mr-1"
              ></span>
              查看更多评论
            </button>
          </div>
          <!-- 评论输入框 -->
          <div class="mt-3">
            <input
              v-model="commentContent"
              type="text"
              placeholder="写下你的评论..."
              class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50"
              @keyup.enter="submitComment"
            />
            <div class="flex justify-end mt-1">
              <button
                class="px-3 py-1 text-sm bg-primary text-white rounded hover:bg-primary/90"
                @click.prevent="submitComment"
                :disabled="!commentContent.trim() || isSubmittingComment"
              >
                <span
                  v-if="isSubmittingComment"
                  class="inline-block animate-spin rounded-full h-3 w-3 border-2 border-white border-t-transparent mr-1"
                ></span>
                发送
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </article>
</template>

<script setup lang="ts">
import { defineProps, ref } from "vue"
import router from "../router"
import { ElMessage } from "element-plus"
// 修复导入语句，移除不存在的工具函数
import {
  type Post,
  type Comment,
  type Reply,
  type UserBaseInfo,
  getComments,
  addComment,
  deleteComment,
  likePost,
  likeComment,
  deletePost,
  toggleCollection
} from "../services/postService"

// ------------------------------
// Props定义（严格匹配Post类型，无any）
// ------------------------------
const props = defineProps<{
  post: Post // 接收帖子数据，Post类型已确保所有字段必传
}>()

// ------------------------------
// 响应式状态（明确类型，避免隐式any）
// ------------------------------
const showComments = ref<boolean>(false)
const comments = ref<Comment[]>([])
const isLoadingComments = ref<boolean>(false)
const hasMoreComments = ref<boolean>(false)
const lastTime = ref<string>("") // 评论分页：最后一条评论时间（与后端对齐）
const offset = ref<number>(0) // 评论分页：偏移量（与后端对齐）
const totalComments = ref<number>(0) // 总评论数（判断是否有更多）

// 评论输入相关
const commentContent = ref<string>("")
const isSubmittingComment = ref<boolean>(false)

// 回复相关（明确类型为Comment/Reply或null）
const replyContent = ref<string>("")
const replyToComment = ref<Comment | null>(null)
const replyToReply = ref<Reply | null>(null) // 支持回复「回复」的二级回复

// 加载状态（避免重复请求，Record类型确保键为number）
const isLiking = ref<boolean>(false)
const isCollecting = ref<boolean>(false)
const isDeleting = ref<Record<number, boolean>>({}) // 评论删除加载状态（键：评论ID）
const commentLikeStatus = ref<Record<number, boolean>>({}) // 评论点赞加载状态（键：评论ID）
const isDeletingPost = ref<boolean>(false) // 帖子删除加载状态
const showMoreOptions = ref<boolean>(false) // 显示更多操作菜单

// ------------------------------
// 工具函数（复用postService的工具函数，避免重复代码）
// ------------------------------
/** 格式化时间为"多久前"（兼容后端时间格式） */
const formatTime = (timeStr: string): string => {
  if (!timeStr) return "未知时间"

  try {
    // 处理后端时间格式（如"2025-09-05 21:25:52" → 转为ISO格式"2025-09-05T21:25:52Z"）
    const normalizedTime = timeStr.replace(/\s+/, "T") + "Z"
    const postTime = new Date(normalizedTime)
    if (isNaN(postTime.getTime())) throw new Error("时间格式无效")

    const now = new Date()
    const diffMs = now.getTime() - postTime.getTime()
    const diffSeconds = Math.floor(diffMs / 1000)

    // 按时间差返回不同格式
    if (diffSeconds < 60) return "刚刚"
    if (diffSeconds < 3600) return `${Math.floor(diffSeconds / 60)}分钟前`
    if (diffSeconds < 86400) return `${Math.floor(diffSeconds / 3600)}小时前`
    if (diffSeconds < 604800) return `${Math.floor(diffSeconds / 86400)}天前`
    // 超过一周显示具体日期（如"2025-09-05"）
    return postTime.toLocaleDateString("zh-CN", {
      month: "2-digit",
      day: "2-digit",
    })
  } catch (error) {
    console.warn("时间格式化失败:", error, "原始时间:", timeStr)
    return timeStr.slice(0, 10) // 失败时返回前10位日期（如"2025-09-05"）
  }
}

/** 去除HTML标签（用于帖子内容预览，避免XSS风险） */
const stripHtml = (html: string): string => {
  return html
    .replace(/<[^>]+>/g, "")
    .replace(/&nbsp;/g, " ")
    .trim()
}

/** 判断是否为当前用户的评论（实际项目需替换为登录用户ID） */
const isOwnComment = (comment: Comment): boolean => {
  // 模拟逻辑：假设当前登录用户UID为1（实际需从用户状态管理中获取）
  const currentUserId = 1
  return comment.uid === currentUserId
}

// ------------------------------
// 核心业务逻辑（补充接口成功判断+参数补全）
// ------------------------------
/** 跳转到帖子详情页（确保post.id存在，TS无报错） */
const goToDetail = () => {
  router.push(`/post/${props.post.id}`) // Post类型中id为必传，无需判断
}

/** 删除帖子 */
const handleDeletePost = async () => {
  if (isDeletingPost.value) return
  
  // 显示确认对话框
  if (!confirm('确定要删除这篇帖子吗？删除后无法恢复。')) {
    return
  }

  try {
    isDeletingPost.value = true
    // 调用删除帖子接口
    await deletePost(props.post.id)
    
    // 删除成功后刷新页面或通知父组件更新列表
    ElMessage.success('帖子删除成功')
    
    // 这里可以根据实际情况选择如何处理删除后的逻辑
    // 例如：如果在列表页，可以通过事件通知父组件移除该帖子
    // emit('post-deleted', props.post.id)
    
    // 简单处理：如果当前是详情页则跳转回首页
    if (window.location.pathname.includes(`/post/${props.post.id}`)) {
      router.push('/')
    } else {
      // 强制刷新当前页面
      location.reload()
    }
  } catch (error) {
    console.error('删除帖子失败:', error)
    ElMessage.error('删除帖子失败，请稍后重试')
  } finally {
    isDeletingPost.value = false
    showMoreOptions.value = false
  }
}

/** 切换更多选项菜单显示/隐藏 */
const toggleMoreOptions = () => {
  if (props.post.canDelete && props.post.canEdit) {
    showMoreOptions.value = !showMoreOptions.value
  }
}

/** 切换帖子点赞状态（补充接口success判断，乐观更新+回滚） */
const toggleLike = async () => {
  if (isLiking.value) return

  const currentLiked = props.post.liked
  const currentLikeCount = props.post.likeCount

  try {
    isLiking.value = true
    // 1. 乐观更新UI（提升用户体验）
    props.post.liked = !currentLiked
    props.post.likeCount = currentLikeCount + (currentLiked ? -1 : 1)

    // 2. 调用点赞接口（严格传递postId和isLike）
    const res = await likePost({
      postId: props.post.id,
      isLike: !currentLiked,
    })

    // 3. 校准状态（接口返回与乐观更新不一致时）

    props.post.liked = res.liked
    props.post.likeCount = res.likeCount

    ElMessage.success(res.liked ? "点赞成功" : "取消点赞成功")
  } catch (error) {
    console.error("帖子点赞失败:", error)
    // 4. 回滚UI（接口失败时恢复原始状态）
    props.post.liked = currentLiked
    props.post.likeCount = currentLikeCount
    ElMessage.error("点赞操作失败，请稍后重试")
  } finally {
    isLiking.value = false
  }
}

/** 切换帖子收藏状态（模拟接口，实际需对接收藏API） */
const toggleCollect = async () => {
  if (isCollecting.value) return

  const currentCollected = props.post.collected

  try {
    isCollecting.value = true
    // 调用实际的收藏接口
    const result = await toggleCollection({
      postId: props.post.id!, // 非空断言：帖子ID必存在
      isCollect: !currentCollected
    })

    // 更新收藏状态
    props.post.collected = result
    ElMessage.success(props.post.collected ? "收藏成功" : "取消收藏成功")
  } catch (error) {
    console.error("帖子收藏失败:", error)
    // 回滚状态
    props.post.collected = currentCollected
    ElMessage.error("收藏操作失败，请稍后重试")
  } finally {
    isCollecting.value = false
  }
}

/** 切换评论区显示/隐藏（首次显示时加载评论） */
const toggleCommentSection = () => {
  showComments.value = !showComments.value
  // 首次打开评论区且无评论数据时，加载第一页评论
  if (showComments.value && comments.value.length === 0) {
    loadComments()
  }
}

/** 加载评论列表（补充res.success判断，与后端分页参数对齐） */
const loadComments = async () => {
  if (isLoadingComments.value) return

  try {
    isLoadingComments.value = true
    // 调用评论接口（传递postId、lastTime、offset，与后端参数完全对齐）
    const res = await getComments({
      postId: props.post.id,
      lastTime: lastTime.value,
      offset: offset.value,
      size: 3, // 每页加载3条评论（与后端约定）
    })

    // 严格判断接口成功（必须同时满足code=0和success=true）
    if (res.code === "0" && res.success && res.data) {
      const newComments = res.data.commentVOS // commentVOS为必传，无需兜底
      // 合并评论数据：首次加载覆盖，后续加载追加
      comments.value =
        lastTime.value === ""
          ? newComments
          : [...comments.value, ...newComments]

      // 更新分页状态（与后端返回的lastTime、offset、count对齐）
      lastTime.value = res.data.lastTime
      offset.value = res.data.offset
      totalComments.value = res.data.count
      // 判断是否有更多评论：已加载数 < 总评论数
      hasMoreComments.value = comments.value.length < totalComments.value
    } else {
      throw new Error(res.message || "获取评论失败")
    }
  } catch (error) {
    console.error("加载评论失败:", error)
    ElMessage.error("加载评论失败，请稍后重试")
  } finally {
    isLoadingComments.value = false
  }
}

/** 加载更多评论（触发分页续加载） */
const loadMoreComments = async () => {
  if (hasMoreComments.value && !isLoadingComments.value) {
    await loadComments()
  }
}

/** 提交一级评论（补充接口success判断，新增评论插入顶部） */
const submitComment = async () => {
  const content = commentContent.value.trim()
  if (!content || isSubmittingComment.value) return

  try {
    isSubmittingComment.value = true
    // 调用提交评论接口（一级评论无需pid和toUid）
    const res = await addComment({
      postId: props.post.id,
      content,
    })

    // 严格判断接口成功
    if (res.code === "0" && res.success && res.data?.comment) {
      // 新增评论插入列表顶部（提升用户体验）
      comments.value.unshift(res.data.comment as Comment)
      // 更新帖子评论数
      props.post.commentCount += 1
      // 清空输入框
      commentContent.value = ""
      ElMessage.success("评论发布成功")
    } else {
      throw new Error(res.message || "评论发布失败")
    }
  } catch (error) {
    console.error("提交评论失败:", error)
    ElMessage.error("评论发布失败，请稍后重试")
  } finally {
    isSubmittingComment.value = false
  }
}

/** 显示回复输入框（支持回复「评论」或「回复」） */
const showReplyInput = (comment: Comment, reply?: Reply) => {
  replyToComment.value = comment
  replyToReply.value = reply || null // 回复「回复」时记录被回复的回复
  replyContent.value = ""
  // 延迟聚焦输入框（确保DOM已更新）
  setTimeout(() => {
    const input = document.querySelector<HTMLInputElement>(
      '[placeholder^="回复 @"]'
    )
    input?.focus()
  }, 100)
}

/** 取消回复（重置回复状态） */
const cancelReply = () => {
  replyToComment.value = null
  replyToReply.value = null
  replyContent.value = ""
}

/** 提交回复（补充toUid参数，与后端对齐） */
const submitReply = async () => {
  const content = replyContent.value.trim()
  if (!content || !replyToComment.value) return

  try {
    isSubmittingComment.value = true
    // 确定被回复者ID：回复「回复」时用replyToReply的uid，否则用replyToComment的uid
    const toUid =
      replyToReply?.value?.userRespDTO?.uid ||
      replyToComment.value?.userRespDTO?.uid

    // 调用提交评论接口（回复需传递pid和toUid）
    const res = await addComment({
      postId: props.post.id,
      content,
      pid: replyToComment.value.id, // 父评论ID（必传）
      toUid, // 被回复者ID（必传，与后端对齐）
    })

    // 严格判断接口成功
    if (res.code === "0" && res.success) {
      // 重新加载评论列表（简化逻辑，实际可局部更新）
      await loadComments()
      // 重置回复状态
      cancelReply()
      // 更新帖子评论数
      props.post.commentCount += 1
      ElMessage.success("回复发布成功")
    } else {
      throw new Error(res.message || "回复发布失败")
    }
  } catch (error) {
    console.error("提交回复失败:", error)
    ElMessage.error("回复发布失败，请稍后重试")
  } finally {
    isSubmittingComment.value = false
  }
}

/** 删除评论（修复：类型安全检查） */
const DeleteComment = async (commentId: number) => {
  if (isDeleting.value[commentId]) return

  try {
    isDeleting.value[commentId] = true
    // 调用删除评论接口
    const res = await deleteComment(commentId)

    // 修复：增强类型检查
    if (
      res !== null &&
      res !== undefined &&
      typeof res === "object" &&
      "code" in res
    ) {
      // 从评论列表中移除删除的评论
      comments.value = comments.value.filter((c) => c.id !== commentId)
      // 更新帖子评论数（确保不小于0）
      props.post.commentCount = Math.max(0, (props.post.commentCount || 0) - 1)
      ElMessage.success("评论删除成功")
    } else {
      throw new Error(
        typeof res === "object" && res !== null && "message" in res
          ? String((res as { message: unknown }).message)
          : "评论删除失败"
      )
    }
  } catch (error) {
    console.error("删除评论失败:", error)
    ElMessage.error("评论删除失败，请稍后重试")
  } finally {
    isDeleting.value[commentId] = false
  }
}

/** 切换评论点赞状态（补充接口success判断，乐观更新+回滚） */
const toggleCommentLike = async (comment: Comment) => {
  if (commentLikeStatus.value[comment.id]) return

  const currentLiked = comment.liked
  const currentLikeCount = comment.likeCount

  try {
    commentLikeStatus.value[comment.id] = true
    // 1. 乐观更新UI
    comment.liked = !currentLiked
    comment.likeCount = currentLikeCount + (currentLiked ? -1 : 1)

    // 2. 调用评论点赞接口
    const res = await likeComment({
      commentId: comment.id,
      isLike: !currentLiked,
    })

    // 3. 校准状态
    if (res) {
      comment.liked = res.liked
      comment.likeCount = res.likeCount
    } else {
      throw new Error("评论点赞失败")
    }
  } catch (error) {
    console.error("评论点赞失败:", error)
    // 4. 回滚UI
    comment.liked = currentLiked
    comment.likeCount = currentLikeCount
    ElMessage.error("评论点赞操作失败，请稍后重试")
  } finally {
    commentLikeStatus.value[comment.id] = false
  }
}
</script>

<style scoped>
/* 图片加载过渡：提升视觉体验 */
img {
  transition: opacity 0.3s ease;
}
img:hover {
  opacity: 0.9;
}

/* 输入框聚焦样式：统一视觉反馈 */
input:focus {
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3);
  outline: none;
}

/* 互动按钮hover效果：平滑过渡 */
button {
  transition: color 0.2s ease;
}
button:hover i {
  color: var(--el-color-primary);
}

/* 评论区边框：弱化视觉干扰 */
.border-t {
  border-top-color: var(--el-border-color-lighter);
}
.border-l-2 {
  border-left-color: var(--el-border-color-lighter);
}
</style>
